//
//  SNUpdateClass.m
//  project
//
//  Created by 黄建华 on 2017/12/30.
//  Copyright © 2017年 黄建华. All rights reserved.
//

#import "SNUpdateClass.h"
#import "AFNetworking.h"
#import "YYJSONHelper.h"
#import "MKNetworkKit.h"
#import "JSON.h"
#import "FileModelEntity.h"
#define UPDATEINDEX 0
@implementation SNUpdateClass
DEF_SINGLETON(SNUpdateClass)

- (instancetype)init {
    self = [super init];
    if (self) {
        NSString *getAppBuildId = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"];
        
        if ([getAppBuildId isEqualToString:@"com.xianweiyun.getfit3"] || [getAppBuildId isEqualToString:@"com.bdk.getfit"]) {
            _app_id = @"1";
        }else if ([getAppBuildId isEqualToString:@"com.bdk.wellgo"]|[getAppBuildId isEqualToString:@"com.xianwei.fitnow"]) {
            _app_id = @"2";
        }else
        {
            _app_id = @"3";
        }
        NSLog(@"_app_id type>>>>>%@", _app_id);
    }
    
    return self;
}

- (void)checkNetSuccess:(NSObjectSimpleBlock)successBlock;
{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSLog(@"当前网络的状态 >>>>%d",status);
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
            {
                //未知网络
                NSLog(@"未知网络");
                if (successBlock) {
                    successBlock(@"0");
                }
            }
                break;
            case AFNetworkReachabilityStatusNotReachable:
            {
                //无法联网
                NSLog(@"无法联网");
                if (successBlock) {
                    successBlock(@"0");
                }
            }
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {
                //手机自带网络
                NSLog(@"当前使用的是2g/3g/4g网络");
                if (successBlock) {
                    successBlock(@"1");
                }
            }
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {
                //WIFI
                NSLog(@"当前在WIFI网络下");
                if (successBlock) {
                    successBlock(@"1");
                }
            }
                break;
        }
        [manager stopMonitoring];
    }];
    
}

// 获取用户信息 token
- (void)getUserInfoWithSuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSString *phone_uuid = [UIDevice currentDevice].identifierForVendor.UUIDString;
    
    if (!phone_uuid) {
        phone_uuid = @"";
    }
    NSString *token = SN_USER.access_token;
    if (token.length <= 0) {
        return;
    }
    NSDictionary *dict = @{@"access_token":token, @"phone_uuid":phone_uuid};
    NSLog(@"获取用户信息参数:%@", dict);
    [KK_FileModelEntity MKNetGET:@"/user/view2" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            NSDictionary *dic = [responseObject objectForKey:@"data"];
            UserInfoModel *model = [UserInfoModel parseString:dic.YYJSONString];
            if (success) {
                success(model);
            }
            SN_USER.total_meal_day = model.total_meal_day;
            SN_USER.first_meal_date = model.first_meal_date;
            SN_USER.goal_weight = model.goal_weight;
            SN_USER.goal_calory = model.goal_calory;
            SN_USER.weight = [dic[@"weight"] floatValue];
            SN_USER.height = [dic[@"height"] integerValue];
            SN_USER.gender = [dic[@"gender"] integerValue];
            SN_USER.birthday = dic[@"birthday"];
            SN_USER.target_step = [dic[@"target_step"] integerValue];
            SN_USER.target_sleep = [dic[@"target_sleep"] integerValue];
            SN_USER.nickName = dic[@"nickname"];
            SN_USER.weightTime = dic[@"last_weight_time"];
            SN_USER.portrait = dic[@"portrait"];
            SN_USER.create_time = dic[@"create_time"];
            SN_USER.sport_days = [dic[@"sport_days"] integerValue];
            
            NSLog(@"运动天数>>>%d 食谱天数>>>%d",SN_USER.sport_days,SN_USER.total_meal_day);
            // 食谱部分同步
             [SN_FoodClass uploadFoodListForService];
            
            // 运动睡眠心率其他数据部分同步
            [[FileModelEntity sharedInstance] syncDataFromServer];
             // 蓝牙部分
            NSDictionary *lastDeviceDic = dic[@"last_device"];
            NSLog(@"lastDeviceDic>>>>>%@", lastDeviceDic);

            if (![lastDeviceDic isEqual:[NSNull null]]) {
                NSString *lastUuid = lastDeviceDic[@"uuid"];
                if (lastUuid.length > 0) {
                    [KK_BLELastDevice setObjectValue:lastDeviceDic[@"uuid"]];
                    [KK_BLELastChip setObjectValue:lastDeviceDic[@"adv_service"]];
                }
            }
            if (![lastDeviceDic isEqual:[NSNull null]]) {
                if ([lastDeviceDic[@"adv_id"]integerValue] > 0) {
                    KK_BLEModel.bleAdvID = [lastDeviceDic[@"adv_id"]integerValue];
                    [LASTCONNECTBLEHEAD setIntValue:KK_BLEModel.bleAdvID];
                    int adv = [lastDeviceDic[@"adv_id"]intValue];
                    SN_USER.heart = intConvertBit(adv, 0);
                    SN_USER.airPressure = intConvertBit(adv, 1);
                    SN_USER.oxygen = intConvertBit(adv, 2);
                    SN_USER.bistoryPressure = intConvertBit(adv, 3);
                    SN_USER.ancs = intConvertBit(adv, 4);
                }
            }

            if (![lastDeviceDic isEqual:[NSNull null]]) {
                if ([lastDeviceDic[@"mac"]length] > 0) {
                    [KK_BLELastDeviceMac setObjectValue:lastDeviceDic[@"mac"]];
                    KK_BLEModel.bleMAC = lastDeviceDic[@"mac"];
                }
            }
            
            if (lastDeviceDic[@"mac"]) {
                int adv = [lastDeviceDic[@"mac"] getIntValue];
                if (adv > 0) {
                    KK_BLEModel.bleAdvID = adv;
                    [LASTCONNECTBLEHEAD setIntValue:KK_BLEModel.bleAdvID];
                    SN_USER.heart = intConvertBit(adv, 0);
                    SN_USER.airPressure = intConvertBit(adv, 1);
                    SN_USER.oxygen = intConvertBit(adv, 2);
                    SN_USER.bistoryPressure = intConvertBit(adv, 3);
                    SN_USER.ancs = intConvertBit(adv, 4);
                    NSLog(@"是否支持心率>>>%i",SN_USER.heart);
                }
            }
            
            [self downImageHeardWith];
            [KK_BLEModel updateToDB];
            [SN_USER updateToDB];
            
            if (model.app_id == 0) {
                [self updateUserAppid:^(id object) {
                } fail:^(id object) {
                }];
            }
            
            [SN_Net getDeviceSFromServerWithSuccess:nil fail:nil];
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

// 第三方登录 或者游客登录
- (void)loginOnWithOpenId:(NSString *)openId withOpenType:(NSString *)openType Success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSDictionary *dic = @{@"openid":openId, @"opentype":openType, @"app_id":_app_id};
    
    [KK_FileModelEntity MKNetPOST:@"/user/open" params:dic success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            NSDictionary *dic = [responseObject objectForKey:@"data"];
            UserInfoModel *model = [UserInfoModel parseString:dic.YYJSONString];
            SHOWMBProgressHUD(SN_Text(@"登陆成功"), nil, nil, NO, 2.0);
            if (success) {
                success(model);
            }
        } else {
            SHOWMBProgressHUD(SN_Text(@"登陆失败"), nil, nil, NO, 2.0);
        }
    } fail:^(id object) {
        SHOWMBProgressHUD(SN_Text(@"登陆失败"), nil, nil, NO, 2.0);
        if (fail) {
            fail(nil);
        }
    }];
}

// 登录接口
- (void)loginOnWithsuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    // 处理耗时操作的代码块...
    NSString *account     = [LOGINACCOUNT getObjectValue];
    NSString *passWord    = [LOGINPASSWORD getObjectValue];
    NSString *passWordMd5 = @"";
    
    if (passWord) {
        passWordMd5 = [self md5:passWord];
    }
    NSDictionary *dict = [NSDictionary dictionary];
    if ([account contains:@"@"]) {
        dict = @{@"email":account,
                 @"password":passWordMd5, @"app_id":_app_id};
    } else {
        dict = @{@"phone":account,
                 @"password":passWordMd5,
                 @"country_code":@"86", @"app_id":_app_id};
    }
    
    [KK_FileModelEntity MKNetPOST:@"/user/login" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            NSDictionary *dic = [responseObject objectForKey:@"data"];
            UserInfoModel *model = [UserInfoModel parseString:dic.YYJSONString];
            SHOWMBProgressHUD(SN_Text(@"登陆成功"), nil, nil, NO, 2.0);
            if (success) {
                success(model);
            }
        } else {
            SHOWMBProgressHUD(SN_Text(@"登陆失败"), nil, nil, NO, 2.0);
        }
    } fail:^(id object) {
        SHOWMBProgressHUD(SN_Text(@"登陆失败"), nil, nil, NO, 2.0);
        if (fail) {
            fail(nil);
        }
    }];
}

//用户信息反馈
- (void)FeedBackWithContent:(NSString *)content Success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSString *sendContent = @"";
    
    if (content.length > 0) {
        sendContent = content;
    }
    NSDictionary *dict = @{@"access_token":SN_USER.access_token, @"content":sendContent};
    
    [KK_FileModelEntity MKNetPOST:@"/support/feedback2" params:dict success:^(id responseObject) {
        if (success) {
            success(responseObject);
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

//获取跑道信息
- (void)getTrackDataWithSuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSDictionary *dict = @{@"access_token":SN_USER.access_token};
    
    [KK_FileModelEntity MKNetGET:@"/sport/track" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            NSArray *arr = [responseObject objectForKey:@"data"];
            NSMutableArray *trackModelArr = [NSMutableArray array];
            NSMutableArray *array = [TrackModel getUserInfoFromDBWithUserID:SN_USER.user_id];
            for (NSDictionary *dic in arr) {
                TrackModel *model = [TrackModel initWithDic:dic];
                for (TrackModel *localModel in array) {
                    if ([localModel.startTime isEqualToString:model.startTime]) {
                        model.shareStrava = localModel.shareStrava;
                    }
                }
                [trackModelArr addObject:model];
            }
            if (success) {
                success(trackModelArr);
            }
        }
    } fail:^(id object) {
        if (fail) {
        }
    }];
}

//上传图片
- (void)uploadImageWithImage:(UIImage *)image WithSuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString             *url     = @"/user/upload-image";
    
    [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", [[NSDate date] dateToString]];
        //上传的参数(上传图片，以文件流的格式)
        [formData appendPartWithFileData:imageData
                                    name:@"image"
                                fileName:fileName
                                mimeType:@"image/jpeg"];
    } success:^(NSURLSessionDataTask *_Nonnull task, id _Nonnull responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            NSArray *arr = responseObject[@"data"][@"urls"];
            SN_USER.portrait = arr.firstObject;
            success(arr);
        } else {
            SHOWMBProgressHUD(nil, responseObject[@"message"], nil, NO, 2);
        }
    } failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
        SHOWMBProgressHUD(HHH_Text([error localizedDescription]), nil, nil, NO, 2.0);
    }];
}

// 上传用户信息 //1 昵称
- (void)updateUserInfoWithSuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSInteger goal_weight = SN_USER.goal_weight;
    if (goal_weight >SN_USER.weight) {
        goal_weight = SN_USER.weight;
    }
    NSInteger goal_calory = SN_USER.goal_calory;
    if (goal_calory == 0) {
        goal_calory = SN_PublicClass.getFoodBmr;
    }
    NSString *height = @"";
    if (SN_USER.height > 0) {
        height = StrByInt(SN_USER.height);
    }
    else
    {
        height = @"175";
    }
    
    NSString *lastTime = @"";
    if (SN_USER.weightTime.length > 0 ) {
        lastTime = SN_USER.weightTime;
    }
    else
    {
        lastTime = [[NSDate date] dateToDayString];
    }
    NSDictionary *userDic = @{@"nickname" : SN_USER.nickName ? SN_USER.nickName : @"",
                              @"sign" : SN_USER.sign ? SN_USER.sign : @"",
                              @"birthday" :SN_USER.birthday,
                              @"height" : height,
                              @"weight" : SN_USER.weight ? @(SN_USER.weight) : @(70),
                              @"gender" : StrByInt(SN_USER.gender),
                              @"portrait" : SN_USER.portrait ? SN_USER.portrait : @"",
                              @"target_step" : StrByInt(SN_USER.target_step ? SN_USER.target_step : 10000),
                              @"target_sleep" : StrByInt(SN_USER.target_sleep ? SN_USER.target_sleep : 640),
                              @"last_weight_time" : lastTime,
                              @"access_token" : SN_USER.access_token,@"goal_weight":StrByInt(goal_weight),@"goal_calory":StrByInt(goal_calory)};
    
    [KK_FileModelEntity MKNetPOST:@"/user/update" params:userDic success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            NSDictionary *dic = [responseObject objectForKey:@"data"];
            UserInfoModel *model = [UserInfoModel parseString:dic.YYJSONString];
            if (success) {
                success(model);
            }
        } else {
            SHOWMBProgressHUD(nil, SN_Text(responseObject[@"message"]), nil, NO, 2.0);
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

// 注册手机
- (void)RegistratWithPhonesuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSString     *passWordMd5 = [self md5:[LOGINPASSWORD getObjectValue]];
    NSDictionary *dict        = @{
                                  @"phone":[LOGINACCOUNT getObjectValue], @"password":passWordMd5,
                                  @"code":[LOGINCODE getObjectValue], @"country_code":[LOGINAREA getObjectValue], @"app_id":_app_id
                                  };
    
    [KK_FileModelEntity MKNetPOST:@"/user/signup" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            NSDictionary *dic = [responseObject objectForKey:@"data"];
            UserInfoModel *model = [UserInfoModel parseString:dic.YYJSONString];
            if (success) {
                success(model);
            }
            SHOWMBProgressHUD(SN_Text(@"注册成功"), nil, nil, NO, 2.0);
        } else {
            SHOWMBProgressHUD(SN_Text(@"注册失败"), nil, nil, NO, 2.0);
        }
    } fail:^(id object) {
        SHOWMBProgressHUD(SN_Text(@"注册失败"), nil, nil, NO, 2.0);
        if (fail) {
            fail(nil);
        }
    }];
}

// 注册邮箱
- (void)RegistratWithEmailsuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSString     *passWordMd5 = [self md5:[LOGINPASSWORD getObjectValue]];
    NSArray      *keysArray   = [LOGINCODE getObjectValue];
    NSDictionary *dict        = @{
                                  @"email":[LOGINACCOUNT getObjectValue], @"password":passWordMd5,
                                  @"keys":[keysArray YYJSONString], @"app_id":_app_id
                                  };
    
    NSLog(@"dict>>>>>>>>>>>>%@", dict);
    [KK_FileModelEntity MKNetPOST:@"/user/signup2" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            if (success) {
                success(responseObject);
            }
            SHOWMBProgressHUD(SN_Text(@"注册成功"), nil, nil, NO, 2.0);
        } else {
            SHOWMBProgressHUD(SN_Text(@"注册失败"), nil, nil, NO, 2.0);
        }
    } fail:^(id object) {
        SHOWMBProgressHUD(SN_Text(@"注册失败"), nil, nil, NO, 2.0);
        if (fail) {
            fail(nil);
        }
    }];
}

// 获取用户是否设置了密保
- (void)getEmailSecretsuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSDictionary *dict = @{
                           @"email":[LOGINACCOUNT getObjectValue], @"app_id":_app_id
                           };
    
    [KK_FileModelEntity MKNetGET:@"/user/get-key-questions" params:dict success:^(id responseObject) {
        SHOWMBProgressHUD(HHH_Text(responseObject[@"message"]), nil, nil, NO, 2.0);
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            if (success) {
                success(responseObject);
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

// 通过密保重新设置密码
- (void)setEmailSecretsuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSString     *passWordMd5 = [self md5:[SERCRETPASSWORD getObjectValue]];
    NSArray      *keysArray   = [LOGINCODE getObjectValue];
    NSDictionary *dict        = @{
                                  @"email":[SERCRETEMAIL getObjectValue], @"password":passWordMd5,
                                  @"keys":[keysArray YYJSONString], @"app_id":_app_id
                                  };
    
    NSLog(@"dict>>>>>>>>>>>>%@", dict);
    [KK_FileModelEntity MKNetPOST:@"/user/reset-pwd-by-keys" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            NSDictionary *dic = responseObject[@"data"];
            NSString *is_success = dic[@"is_success"];
            if (is_success.integerValue == 1) {
                if (success) {
                    success(responseObject);
                }
                SHOWMBProgressHUD(HHH_Text(@"密码修改成功"), nil, nil, NO, 2.0);
            } else {
                SHOWMBProgressHUD(HHH_Text(@"密保错误"), nil, nil, NO, 2.0);
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

// 获取设备在线信息
- (void)getDeviceSFromServerWithSuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSLog(@"获取设备在线信息");
    [KK_FileModelEntity MKNetPOST:@"/support/devices" params:nil success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            NSDictionary *dic = [responseObject objectForKey:@"data"];
            NSMutableArray *arr = [NSMutableArray array];
            NSMutableArray *advArr = [NSMutableArray array];
            for (NSDictionary *dic in responseObject[@"data"]) {
                NSString *nameStr = dic[@"device_name"];
                int  advS = [dic[@"adv_id"]intValue];
                NSString *adv = StrByInt(advS);
                NSInteger currentAdv = [LASTCONNECTBLEHEAD getIntValue];
                if (advS == currentAdv && advS != 0  && currentAdv != 0) {
                    NSString *extra = dic[@"extra"];
                    NSDictionary *dic2 = [self dictionaryWithJsonString:extra];
                    BOOL anti_drop_state = [dic2[@"anti_drop_state"]boolValue];
                    SN_USER.showBleLost = anti_drop_state;
                    BOOL lanuage = [dic2[@"default_language"]boolValue];
                    SN_USER.showLanuage = lanuage;
                    BOOL wallpaper = [dic2[@"wallpaper"]boolValue];
                    BOOL isSupportSportMode = [dic2[@"sport_mode_data"] boolValue];
                    BOOL isSupportSettingTimeUnit = [dic2[@"time_format"] boolValue];
                    BOOL isSupportTianMao = [dic2[@"is_support_tianmao"] boolValue];
                    BOOL isSupportFood = [dic2[@"is_support_food"] boolValue];
                    NSInteger screen_type = [dic2[@"screen_type"]integerValue];
                    NSLog(@"advS:%d",advS);
                    NSLog(@"isSupportFood:%d",isSupportFood);
                    SN_USER.screen_type = screen_type;
                    SN_USER.wallpaper = wallpaper;
                    SN_USER.isSupportSportMode = isSupportSportMode;
                    SN_USER.isSupportSettingTimeUnit = isSupportSettingTimeUnit;
                    SN_USER.isSupportTianMao = isSupportTianMao;
                    SN_USER.isSupporFood = isSupportFood;
                    NSString *sss = dic2[@"language"];
                    NSArray *array = [self arrayWithJsonString:sss];
                    NSLog(@"lanuageArray >>>>>>>%@ showLanuage>>>%i",array,lanuage);
                    SN_USER.lanuageArray = [NSArray arrayWithArray:array];
                    [SN_USER updateToDB];
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"updateOnliceDevice" object:nil];
                    // 标识已经请求过
                    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isHadRequestBleFunction"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    
                    NSLog(@"连接：%@",dic);
                    
                    if (self.block) {
                        self.block(isSupportFood);
                    }
                }
                
                int apptype = [dic[@"apptype"]intValue];
                int currentAppid = SN_Net.app_id.intValue;
                BOOL find = intConvertBit(apptype, currentAppid-1);
                
                // BOOL isGetFitPro = [SN_Net.app_id intValue] == 1 && ((apptype >> 0) & 0x01) == 1;
                // BOOL isWellGo = [SN_Net.app_id intValue] == 2 && ((apptype >> 1) & 0x01) == 1;
                // BOOL isLexe = [SN_Net.app_id intValue] == 3 && ((apptype >> 2) & 0x01) == 1;
                // BOOL isSwissFitLite = [SN_Net.app_id intValue] == 4 && ((apptype >> 3) & 0x01) == 1;
                // isGetFitPro || isWellGo || isLexe || isSwissFitLite
                if (find) {
                    if (![arr containsObject:nameStr]) {
                        [arr addObject:nameStr];
                    }
                    if (![advArr containsObject:adv]) {
                        [advArr addObject:adv];
                    }
                }
            }
            
            [[NSUserDefaults standardUserDefaults] setObject:advArr forKey:@"DeviceadvArr"];
            [[NSUserDefaults standardUserDefaults] setObject:arr forKey:@"DeviceNameArr"];
            [[NSUserDefaults standardUserDefaults] synchronize];

            if (success) {
                success(dic);
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

// 获取设备升级信息
- (void)getDeviceUpdateInfoFromServerWithSuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSDictionary         *param   = @{@"adv_id" : @(KK_BLEModel.bleAdvID), @"customid" : @(KK_BLEModel.bleCustomerID), @"upgradeid":@(KK_BLEModel.deviceID)};
    
    [KK_FileModelEntity MKNetGET:@"/support/hwversion2" params:param success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            NSDictionary *dic = [responseObject objectForKey:@"data"];
            KK_BLEModel.bleOnlineVersion = [dic[@"version"] integerValue];
            KK_BLEModel.download_url = dic[@"download_url"];
            KK_BLEModel.chip = [dic[@"chip"] lowercaseString];
//            NSLog(@"KK_BLEModel.bleOnlineVersion===%ld,KK_BLEModel.download_url==%@", KK_BLEModel.bleOnlineVersion, KK_BLEModel.download_url);
            [KK_BLEModel updateToDB];
            success(nil);
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

//获取所有APP版本状态
- (void)getAppUpdateInfoFromServerWithSuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    [KK_FileModelEntity MKNetGET:@"/support/appversion2" params:nil success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            NSArray *arr = [responseObject objectForKey:@"data"];
            for (NSDictionary *dic in arr) {
                NSString *appName = [NSString stringWithFormat:@"ios_%@", APP_NAME];
                if ([appName isEqualToString:dic[@"app_name"]]) {
                    NSString *appStoreVersionShow = dic[@"version_name"];
                    SN_USER.lastOnlineAppVersion = appStoreVersionShow;
                    [SN_USER updateToDB];
                    success(dic);
                    break;
                }
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

- (void)updateEveryModelWithType:(HJUpdateModelUpdateState)type {
    NSMutableArray *array;
    
    if (type == HJUpdateStep) {
        array = [SNEveryDayModelHelp getModelWithOutUpdateFromLocalDBStep].mutableCopy;
        if (array.count == 0) {
            //            [self updateDataWithType:type];
        } else {
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateHistoryStepWithArr:) object:array];
            [self performSelector:@selector(updateHistoryStepWithArr:) withObject:array afterDelay:10.0];
        }
    }
    
    if (type == HJUpdateSleep) {
        array = [SNEveryDayModelHelp getModelWithOutUpdateFromLocalDBSleep].mutableCopy;
        if (array.count == 0) {
            //            [self updateDataWithType:type];
        } else {
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateHistorySleepWithArr:) object:array];
            [self performSelector:@selector(updateHistorySleepWithArr:) withObject:array afterDelay:10.0];
        }
    }
    
    if (type == HJUpdateHeart) {
        if (!SN_USER.heart) {
            return;
        }
        array = [SNEveryDayModelHelp getModelWithOutUpdateFromLocalDBHeart].mutableCopy;
        if (array.count == 0) {
            //            [self updateDataWithType:type];
        } else {
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateHistoryHeartWithArr:) object:array];
            [self performSelector:@selector(updateHistoryHeartWithArr:) withObject:array afterDelay:10.0];
        }
    }
    
    if (type == HJUpdateOX) {
        if (!SN_USER.oxygen) {
            return;
        }
        array = [SNEveryDayModelHelp getModelWithOutUpdateFromLocalDBOx].mutableCopy;
        if (array.count == 0) {
            //            [self updateDataWithType:type];
        } else {
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateHistoryOXWithArr:) object:array];
            [self performSelector:@selector(updateHistoryOXWithArr:) withObject:array afterDelay:10.0];
        }
    }
    
    if (type == HJUpdateBp) {
        if (!SN_USER.bistoryPressure) {
            return;
        }
        array = [SNEveryDayModelHelp getModelWithOutUpdateFromLocalDBBp].mutableCopy;
        if (array.count == 0) {
            //            [self updateDataWithType:type];
        } else {
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateHistoryBpWithArr:) object:array];
            [self performSelector:@selector(updateHistoryBpWithArr:) withObject:array afterDelay:10.0];
        }
    }
}

- (void)updateHistoryStepWithArr:(NSMutableArray *)array {
    if (array.count > 0) {  // 先把本地数据昨天之前的数据都上传到服务器
        SportModel *model = [array firstObject];
        [self updateSport:model success:^(id object) {
        } fail:^(id object) {
        }];
        [array removeObjectAtIndex:0];
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateHistoryStepWithArr:) object:array];
        [self performSelector:@selector(updateHistoryStepWithArr:) withObject:array afterDelay:5.0];
    }
    if (array.count == 0) {
        //        [self updateDataWithType:HJUpdateStep];
    }
}

- (void)updateHistorySleepWithArr:(NSMutableArray *)array {
    if (array.count > 0) { // 先把本地数据昨天之前的数据都上传到服务器
        SleepModel *model = [array firstObject];
        [self updateSleep:model success:^(id object) {
        } fail:^(id object) {
        }];
        [array removeObjectAtIndex:0];
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateHistorySleepWithArr:) object:array];
        [self performSelector:@selector(updateHistorySleepWithArr:) withObject:array afterDelay:5.0];
    }
    if (array.count == 0) {
        //        [self updateDataWithType:HJUpdateSleep];
    }
}

- (void)updateHistoryHeartWithArr:(NSMutableArray *)array {
    if (array.count > 0) { // 先把本地数据昨天之前的数据都上传到服务器
        HeartModel *model = [array firstObject];
        [self updateHeart:model success:^(id object) {
        } fail:^(id object) {
        }];
        [array removeObjectAtIndex:0];
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateHistoryHeartWithArr:) object:array];
        [self performSelector:@selector(updateHistoryHeartWithArr:) withObject:array afterDelay:5.0];
    }
    if (array.count == 0) {
        //        [self updateDataWithType:HJUpdateHeart];
    }
}

- (void)updateHistoryOXWithArr:(NSMutableArray *)array {
    if (array.count > 0) { // 先把本地数据昨天之前的数据都上传到服务器
        OxModel *model = [array firstObject];
        [self updateOx:model success:^(id object) {
        } fail:^(id object) {
        }];
        [array removeObjectAtIndex:0];
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateHistoryOXWithArr:) object:array];
        [self performSelector:@selector(updateHistoryOXWithArr:) withObject:array afterDelay:5.0];
    }
    if (array.count == 0) {
        //        [self updateDataWithType:HJUpdateOX];
    }
}

- (void)updateHistoryBpWithArr:(NSMutableArray *)array {
    if (array.count > 0) { // 先把本地数据昨天之前的数据都上传到服务器
        BpModel *model = [array firstObject];
        [self updateBp:model success:^(id object) {
        } fail:^(id object) {
        }];
        [array removeObjectAtIndex:0];
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateHistoryBpWithArr:) object:array];
        [self performSelector:@selector(updateHistoryBpWithArr:) withObject:array afterDelay:5.0];
    }
    if (array.count == 0) {
        //        [self updateDataWithType:HJUpdateBp];
    }
}

- (void)updateDataWithType:(HJUpdateModelUpdateState)type {
    NSString *dateStrNow = [[NSDate date] dateToDayString];
    
    if (type == HJUpdateStep) {
        //        if (SN_PublicClass.todaySport.step != stepS.integerValue) {
        [self updateSport:SN_PublicClass.todaySport success:^(id object) {
        } fail:^(id object) {
        }];
        //        }
    }
    if (type == HJUpdateSleep) {
        //        if (SN_PublicClass.todaySleep.durations != sleepS.integerValue) {
        [self updateSleep:SN_PublicClass.todaySleep success:^(id object) {
        } fail:^(id object) {
        }];
        //        }
    }
    if (type == HJUpdateHeart) {
        //        if (SN_PublicClass.todayHeart.heartAllValueArray.count != heartS.integerValue) {
        [self updateHeart:SN_PublicClass.todayHeart success:^(id object) {
        } fail:^(id object) {
        }];
        //        }
    }
    if (type == HJUpdateOX) {
        //        if (SN_PublicClass.todayOx.oxsuArrayAuto.count != oxS.integerValue) {
        [self updateOx:SN_PublicClass.todayOx success:^(id object) {
        } fail:^(id object) {
        }];
        //        }
    }
    if (type == HJUpdateBp) {
        //        if (SN_PublicClass.todayBp.bpSuArray.count != bpS.integerValue) {
        [self updateBp:SN_PublicClass.todayBp success:^(id object) {
        } fail:^(id object) {
        }];
        //        }
    }
}

- (void)updateSport:(SportModel *)model success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    if (!KK_BLEModel.bleMAC) {
        return;
    }
    NSDictionary *dataDict = @{@"step" : model.stepArray,
                               @"distance" :model.distanceArray,
                               @"cal" : model.calorArray};
    NSDictionary *dict = @{@"mac" : KK_BLEModel.bleMAC,
                           @"date" : model.dateString,
                           @"duration" : StrByInt(model.stepDuration),
                           @"step" : StrByInt(model.step),
                           @"distance" : StrByInt(model.distance),
                           @"calory" : StrByInt(model.calory),
                           @"data" : [dataDict YYJSONString]};
    
    if (SN_USER.access_token) {
        NSDictionary *upload = @{@"access_token" : SN_USER.access_token,
                                 @"data" : [@[dict] YYJSONString]};
        [self uploadDataToServer:HJUpdateStep dict:upload success:^(id object)
         {
             NSUserDefaults *sss = [NSUserDefaults standardUserDefaults];
             [sss setValue:StrByInt(model.step) forKey:[NSString stringWithFormat:@"%@step", object]];
             [sss synchronize];
             NSDate *updateDate = [NSDate dateByString:object];
             NSDate *nextDay = [updateDate dateAfterDay:UPDATEINDEX];
             NSString *nextDayString = [nextDay dateToDateWithDate];
             [LASTUPDATESTEP setObjectValue:nextDayString];
             NSString *uploadString = [updateDate dateToDateWithDate];
             NSString *todayString = [[NSDate date]dateToDateWithDate];
             if ([uploadString isEqualToString:todayString]) {
                 [LASTUPDATESTEP setObjectValue:todayString];
             }
             if (success) {
                 success(object);
             }
         }                  fail:^(id object) {
         }];
    }
}

- (void)updateSleep:(SleepModel *)model success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    if (!KK_BLEModel.bleMAC) {
        return;
    }
    //    if (model.durations == 0) {
    //        return;
    //    }
    NSMutableArray *sleepData = [NSMutableArray array];
    for (SleepSubModel *sleepmodel in model.sleepsubArray) {
        NSDictionary *dic = @{@"startTime" :sleepmodel.substartTime,
                              @"endTime" : sleepmodel.subendTime,
                              @"sleepData" : sleepmodel.subsleepData};
        [sleepData addObject:dic];
    }
    NSDictionary *dict = @{@"mac" : KK_BLEModel.bleMAC,
                           @"date" : model.dateString,
                           @"duration" : StrByInt(model.durations),
                           @"deep" : StrByInt(model.deeps),
                           @"light" : StrByInt(model.lights),
                           @"sober" : StrByInt(model.sobers),
                           @"data" : [sleepData YYJSONString]};
    if (SN_USER.access_token) {
        NSDictionary *upload = @{@"access_token" : SN_USER.access_token,
                                 @"data" : [@[dict] YYJSONString]};
        [self uploadDataToServer:HJUpdateSleep dict:upload success:^(id object)
         {
             NSUserDefaults *sss = [NSUserDefaults standardUserDefaults];
             [sss setValue:StrByInt(model.durations) forKey:[NSString stringWithFormat:@"%@sleep", object]];
             [sss synchronize];
             NSDate *updateDate = [NSDate dateByString:object];
             NSDate *nextDay = [updateDate dateAfterDay:UPDATEINDEX];
             NSString *nextDayString = [nextDay dateToDateWithDate];
             [LASTUPDATESLEEP setObjectValue:nextDayString];
             
             NSString *uploadString = [updateDate dateToDateWithDate];
             NSString *todayString = [[NSDate date]dateToDateWithDate];
             if ([uploadString isEqualToString:todayString]) {
                 [LASTUPDATESLEEP setObjectValue:todayString];
             }
             
             if (success) {
                 success(object);
             }
         }                  fail:^(id object) {
         }];
    }
}

- (void)updateOx:(OxModel *)model success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    if (!KK_BLEModel.bleMAC) {
        return;
    }
    NSMutableArray *oxArray = [NSMutableArray array];
    
    for (oxSubModel *oxModel in model.oxsuArrayAuto) {
        if (oxModel.oxValue > 0) {
            NSDictionary *dic = @{@"time" :[oxModel.updateTime componentsSeparatedByString:@" "][1],
                                  @"value" : StrByInt(oxModel.oxValue)};
            [oxArray addObject:dic];
        }
    }
    if (oxArray.count == 0) {
        return;
    }
    NSDictionary *dict = @{@"type" : StrByInt(1),
                           @"max" : StrByInt(model.oxMax),
                           @"min" : StrByInt(model.oxMin),
                           @"average" :StrByInt(model.oxAve),
                           @"times" : StrByInt(oxArray.count),
                           @"data" : [oxArray YYJSONString],
                           @"date" : model.dateString,
                           @"mac" : KK_BLEModel.bleMAC};
    NSArray *array = [NSArray arrayWithObjects:dict, nil];
    if (SN_USER.access_token) {
        NSDictionary *upload = @{@"access_token" : SN_USER.access_token,
                                 @"type":StrByInt(1),
                                 @"data" : [array YYJSONString]};
        [self uploadDataToServer:HJUpdateOX dict:upload success:^(id object)
         {
             NSUserDefaults *sss = [NSUserDefaults standardUserDefaults];
             [sss setValue:StrByInt(model.oxsuArrayAuto.count) forKey:[NSString stringWithFormat:@"%@ox", object]];
             [sss synchronize];
             NSDate *updateDate = [NSDate dateByString:object];
             NSDate *nextDay = [updateDate dateAfterDay:UPDATEINDEX];
             NSString *nextDayString = [nextDay dateToDateWithDate];
             [LASTUPDATEOX setObjectValue:nextDayString];
             
             NSString *uploadString = [updateDate dateToDateWithDate];
             NSString *todayString = [[NSDate date]dateToDateWithDate];
             if ([uploadString isEqualToString:todayString]) {
                 [LASTUPDATEOX setObjectValue:todayString];
             }
             if (success) {
                 success(object);
             }
         }                  fail:^(id object) {
         }];
    }
}

- (void)updateBp:(BpModel *)model success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    if (!KK_BLEModel.bleMAC) {
        return;
    }
    NSMutableArray *bpArray = [NSMutableArray array];
    
    for (bpSubModel *bpModel in model.bpSuArray) {
        if (bpModel.SBPValue && bpModel.DBPValue) {
            NSInteger sbp = 0;
            NSInteger dbp = 0;
            if (bpModel.SBPValue > bpModel.DBPValue) {
                sbp = bpModel.SBPValue;
                dbp = bpModel.DBPValue;
            } else {
                sbp = bpModel.DBPValue;
                dbp = bpModel.SBPValue;
            }
            
            NSDictionary *dic = @{@"time" :[bpModel.updateTime componentsSeparatedByString:@" "][1],
                                  @"systolic" : StrByInt(sbp),
                                  @"diastolic" :StrByInt(dbp)};
            [bpArray addObject:dic];
        }
    }
    if (bpArray.count == 0) {
        return;
    }
    int          ave   = (model.SBPAve + model.DBPAve) /2;
    NSDictionary *dict = @{@"type" : StrByInt(3),
                           @"max" : StrByInt(model.SBPAve),
                           @"min" : StrByInt(model.DBPAve),
                           @"average" :StrByInt(ave),
                           @"times" : StrByInt(model.bpSuArray.count),
                           @"data" : [bpArray YYJSONString],
                           @"date" : model.dateString,
                           @"mac" : KK_BLEModel.bleMAC};
    NSArray *array = [NSArray arrayWithObjects:dict, nil];
    if (SN_USER.access_token) {
        NSDictionary *upload = @{@"access_token" : SN_USER.access_token,
                                 @"type":StrByInt(3),
                                 @"data" : [array YYJSONString]};
        [self uploadDataToServer:HJUpdateBp dict:upload success:^(id object)
         {
             NSUserDefaults *sss = [NSUserDefaults standardUserDefaults];
             [sss setValue:StrByInt(model.bpSuArray.count) forKey:[NSString stringWithFormat:@"%@bp", object]];
             [sss synchronize];
             NSDate *updateDate = [NSDate dateByString:object];
             NSDate *nextDay = [updateDate dateAfterDay:UPDATEINDEX];
             NSString *nextDayString = [nextDay dateToDateWithDate];
             [LASTUPDATEBP setObjectValue:nextDayString];
             
             NSString *uploadString = [updateDate dateToDateWithDate];
             NSString *todayString = [[NSDate date]dateToDateWithDate];
             if ([uploadString isEqualToString:todayString]) {
                 [LASTUPDATEBP setObjectValue:todayString];
             }
             if (success) {
                 success(object);
             }
         }                  fail:^(id object) {
         }];
    }
}

//1：血氧，2：心率，3：收缩压，4：舒展压
- (void)updateHeart:(HeartModel *)model success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    if (!KK_BLEModel.bleMAC) {
        return;
    }
    NSMutableArray *heartAuto  = [NSMutableArray arrayWithArray:model.heartsuArrayAuto];
    NSMutableArray *heartCheck = [NSMutableArray arrayWithArray:model.heartSuArrayCheck];
    NSMutableArray *heartArray = [NSMutableArray array];
    
    for (int k = 0; k < heartAuto.count; k++) {
        HeartSubModel *heartModel = [heartAuto objectAtIndex:k];
        if (heartModel.heartValue > 0) {
            NSDictionary *dic = @{@"time" :[heartModel.updateTime componentsSeparatedByString:@" "][1],
                                  @"value" : StrByInt(heartModel.heartValue)
                                  , @"type":@"1"};
            [heartArray addObject:dic];
        }
    }
    for (int k = 0; k < heartCheck.count; k++) {
        HeartSubModel *heartModel = [heartCheck objectAtIndex:k];
        if (heartModel.heartValue > 0) {
            NSDictionary *dic = @{@"time" :[heartModel.updateTime componentsSeparatedByString:@" "][1],
                                  @"value" : StrByInt(heartModel.heartValue)
                                  , @"type":@"0"};
            [heartArray addObject:dic];
        }
    }
    //    if (heartArray.count == 0) {
    //        return;
    //    }
    //    NSLog(@"heartArray>>>>>%@", heartArray);
    NSDictionary *dict = @{@"type" : StrByInt(2),
                           @"max" : StrByInt(model.heartMax),
                           @"min" : StrByInt(model.heartMin),
                           @"average" :StrByInt(model.heartAve),
                           @"times" : StrByInt(heartArray.count),
                           @"data" : [heartArray YYJSONString],
                           @"date" : model.dateString,
                           @"mac" : KK_BLEModel.bleMAC};
    NSArray *array = [NSArray arrayWithObjects:dict, nil];
    if (SN_USER.access_token) {
        NSDictionary *upload = @{@"access_token" : SN_USER.access_token,
                                 @"type":StrByInt(2),
                                 @"data" : [array YYJSONString]};
        [self uploadDataToServer:HJUpdateHeart dict:upload success:^(id object)
         {
             NSUserDefaults *sss = [NSUserDefaults standardUserDefaults];
             [sss setValue:StrByInt(model.heartAllValueArray.count) forKey:[NSString stringWithFormat:@"%@heart", object]];
             [sss synchronize];
             NSDate *updateDate = [NSDate dateByString:object];
             NSDate *nextDay = [updateDate dateAfterDay:UPDATEINDEX];
             NSString *nextDayString = [nextDay dateToDateWithDate];
             [LASTUPDATEHEART setObjectValue:nextDayString];
             
             NSString *uploadString = [updateDate dateToDateWithDate];
             NSString *todayString = [[NSDate date]dateToDateWithDate];
             if ([uploadString isEqualToString:todayString]) {
                 [LASTUPDATEHEART setObjectValue:todayString];
             }
             if (success) {
                 success(object);
             }
         }                  fail:^(id object) {
         }];
    }
}

// 上传
- (void)uploadDataToServer:(HJUpdateModelUpdateState)link dict:(NSDictionary *)dict
                   success:(NSObjectSimpleBlock)success
                      fail:(NSObjectSimpleBlock)fail {
    NSString *type = @"";
    NSString *url  = @"";
    
    if (link == HJUpdateStep) {
        url  = @"/sport/upload";
        type = @"运动数据";
    } else if (link == HJUpdateSleep) {
        url  = @"/sleep/upload";
        type = @"睡眠数据";
    } else if (link == HJUpdateHeart) {
        url  = @"/examination/uploadday";
        type = @"心率数据";
    } else if (link == HJUpdateOX) {
        url  = @"/examination/uploadday";
        type = @"血氧数据";
    } else if (link == HJUpdateBp) {
        url  = @"/examination/uploadday";
        type = @"血压数据";
    }
    
    [KK_FileModelEntity MKNetPOST:url params:dict success:^(id responseObject) {
        NSLog(@" AFHTTPSessionManager type:%@ JSON: %@", type, responseObject);
        NSDictionary *dic = [responseObject objectForKey:@"data"];
        NSArray *array = [dic valueForKey:@"success_dates"];
        NSString *sss = @"";
        if (array) {
            sss = [array firstObject];
        }
        [SN_PublicClass writefileWith:[NSString stringWithFormat:@"日期:%@ 类型:%@ 上传成功", sss, type]];
        if (success) {
            success(sss);
        }
    } fail:^(id object) {
        [SN_PublicClass writefileWith:[NSString stringWithFormat:@"上传失败 类型:%@", type]];
    }];
}

//获取天气接口
- (void)getWeatherWith:(NSDictionary *)dic Success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    [KK_FileModelEntity MKNetPOST:@"/support/weather-aggregate" params:dic success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            if (success) {
                success(responseObject);
            }
        }
    } fail:^(id responseObject) {
        if (fail) {
            fail(nil);
        }
    }];
}

- (void)uploadDataToServer:(NSString *)link dict:(NSDictionary *)dict image:(UIImage *)image imageName:(NSString *)imageName success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager POST:link parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *data = UIImagePNGRepresentation(image);
        NSString *fileName = imageName;
        [formData appendPartWithFileData:data name:@"track_image" fileName:fileName mimeType:@"image/png"];
    }
          success:^(NSURLSessionDataTask *_Nonnull task, id _Nonnull responseObject) {
              success(responseObject);
          }
          failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
              fail(error);
          }];
}

- (void)updateUserAppid:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSDictionary *dict = @{@"access_token":SN_USER.access_token, @"app_id":_app_id};
    
    [KK_FileModelEntity MKNetPOST:@"/user/userdevice" params:dict success:^(id responseObject) {
        NSLog(@"设置用户所属的app_id>>>>>%@", responseObject);
        if (success) {
            success(responseObject);
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

//上传用户手环信息 先上传用户手环信息 再更新用户信息...
- (void)updateBleDevice:(GetOrRemoveEquipmentInfoState)type Success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSDictionary *dict = @{};
    if (type == GetEquipmentInfo) {
        dict = @{
                               @"access_token":SN_USER.access_token,
                               @"mac":KK_BLEModel.bleMAC ? KK_BLEModel.bleMAC : @"",
                               @"device_name":KK_BLEModel.bleName ? KK_BLEModel.bleName : @"",
                               @"adv_id":StrByInt(KK_BLEModel.bleAdvID) ? StrByInt(KK_BLEModel.bleAdvID) : @"",
                               @"function":StrByInt(KK_BLEModel.function) ? StrByInt(KK_BLEModel.function) : @"",
                               @"uuid":[KK_BLELastDevice getObjectValue] ? [KK_BLELastDevice getObjectValue] : @"",
                               @"adv_service":[KK_BLELastChip getObjectValue] ? [KK_BLELastChip getObjectValue] : @"",
                               };
    } else {
        dict = @{
                               @"access_token":SN_USER.access_token,
                               @"mac": @"",
                               @"device_name":@"",
                               @"adv_id": [NSNumber numberWithInt:0],
                               @"function":[NSNumber numberWithInt:0],
                               @"uuid":@"",
                               @"adv_service":@"",
                               };
    }
    
    NSLog(@"上传用户手环信息参数>>>>>%@", dict);
    [KK_FileModelEntity MKNetPOST:@"/user/userdevice" params:dict success:^(id responseObject) {
        NSLog(@"上传用户手环信息返回值>>>>>%@", responseObject);
        if (type == GetEquipmentInfo) {
            
        } else {
            // KK_BLEModel.bleMAC 制空
            KK_BLEModel.bleMAC = @"";
            [KK_BLELastDeviceMac setObjectValue:@""];
        }
        
        if (success) {
            success(responseObject);
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

//MD5加密
- (NSString *)md5:(NSString *)input {
    const char    *cStr = [input UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5(cStr, strlen(cStr), digest);   // This is the md5 call
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    return output;
}

- (void)uploadUserLog {
    NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[LogManager sharedInstance].basePath error:nil];
    
    files = [files sortedArrayUsingComparator:^NSComparisonResult (id _Nonnull obj1, id _Nonnull obj2) {
        return [obj2 compare:obj1];
    }];
    NSString *fileName = [NSString string];
    NSString *filePath = [NSString string];
    if (files.count == 1) {
        return;
    }
    for (int i = 0; i < files.count; i++) {
        if (i < files.count-1) {
            fileName = files[i+1];
            filePath = [NSString stringWithFormat:@"%@%@", [LogManager sharedInstance].basePath, fileName];
            AFHTTPSessionManager *manager    = [AFHTTPSessionManager manager];
            NSInteger            error_times = [[NSUserDefaults standardUserDefaults] integerForKey:fileName];
            NSString             *url        = @"/support/userlog";
            NSDictionary         *param      = @{@"access_token":SN_USER.access_token,
                                                 @"user_id":SN_USER.user_id,
                                                 @"model":[NSString iphoneType],
                                                 @"brand":@"apple",
                                                 @"appversion":SN_USER.currentAppVersion,
                                                 @"apptype":@"2",
                                                 @"systemversion":[UIDevice currentDevice].systemVersion,
                                                 @"device_uuid":[UIDevice currentDevice].identifierForVendor.UUIDString,
                                                 @"date":[NSDate date].dateToDayString,
                                                 @"error_times":[NSString stringWithFormat:@"%ld", (long)error_times]};
            DEF_WEAKSELF_(SNUpdateClass)
            [manager POST:url parameters: param constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
                NSData *data = [NSData dataWithContentsOfFile:filePath];
                [formData appendPartWithFileData:data name:@"logfile" fileName:fileName mimeType:@"txt"];
            } success:^(NSURLSessionDataTask *_Nonnull task, id _Nonnull responseObject) {
                if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
                    [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
                    [weakSelf uploadUserLog];
                } else {
                    //SHOWMBProgressHUD(nil, responseObject[@"message"], nil, NO, 2);
                }
            } failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
                //SHOWMBProgressHUD(nil, HHH_Text([error localizedDescription]), nil, NO, 2.0);
            }];
        } else {
            return;
        }
    }
}

- (void)feedBackUserLog {
    NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[LogManager sharedInstance].basePath error:nil];
    
    files = [files sortedArrayUsingComparator:^NSComparisonResult (id _Nonnull obj1, id _Nonnull obj2) {
        return [obj2 compare:obj1];
    }];
    NSString             *fileName = files.firstObject;
    NSString             *filePath = [NSString stringWithFormat:@"%@%@", [LogManager sharedInstance].basePath, fileName];
    AFHTTPSessionManager *manager  = [AFHTTPSessionManager manager];
    NSString             *url      = @"/support/userlog";
    NSDictionary         *param    = @{@"access_token":SN_USER.access_token,
                                       @"user_id":SN_USER.user_id,
                                       @"model":[NSString iphoneType],
                                       @"brand":@"apple",
                                       @"appversion":SN_USER.currentAppVersion,
                                       @"apptype":@"2",
                                       @"systemversion":[UIDevice currentDevice].systemVersion,
                                       @"device_uuid":[UIDevice currentDevice].identifierForVendor.UUIDString,
                                       @"date":[NSDate date].dateToDayString,
                                       @"error_times":[NSString stringWithFormat:@"%ld", (long)ErrorTimes]};
    
    [manager POST:url parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *data = [NSData dataWithContentsOfFile:filePath];
        [formData appendPartWithFileData:data name:@"logfile" fileName:fileName mimeType:@"txt"];
    } success:^(NSURLSessionDataTask *_Nonnull task, id _Nonnull responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
        } else {
            SHOWMBProgressHUD(nil, responseObject[@"message"], nil, NO, 2);
        }
    } failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
    }];
}

//下载头像
- (void)downImageHeardWith {
    NSURL                *headUrl    = [NSURL URLWithString:SN_USER.portrait];
    SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader];
    
    [downloader downloadImageWithURL:headUrl
                             options:0
                            progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                                // progression tracking code
                            }
                           completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
                               if (image && finished) {
                                   // do something with image
                                   NSString *filePath = [[XYSandbox libCachePath] stringByAppendingPathComponent:KK_HeadImage];;
                                   BOOL ok = [[NSFileManager defaultManager] createFileAtPath:filePath contents:data attributes:nil];
                                   if (ok) {
                                       NSLog(@"用户头像下载成功>>>>");
                                   }
                               }
                           }];
}

/***********************************好友功能接口***************************************/
// 查找用户 要查找的邮箱/手机号/ID
- (void)friendWithSearch:(NSString *)searchInfo success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSString *search = searchInfo;
    
    if (!search) {
        search = @"";
    }
    NSDictionary *dict = @{@"access_token":SN_USER.access_token, @"key":search};
    //    NSLog(@"dict>>>>%@", dict);
    [KK_FileModelEntity MKNetGET:@"/user/search" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            NSArray *array = responseObject[@"data"];
            //            NSLog(@"好友功能>>>>>>>>查找用户  %@", responseObject);
            if (success) {
                success([array firstObject]);
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

// 用户主页 用户ID
- (void)friendWithSearchHomePage:(NSString *)userId success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSString *search = userId;
    
    if (!search) {
        search = @"";
    }
    NSDictionary *dict = @{@"access_token":SN_USER.access_token, @"user_id":search};
    //    NSLog(@"dict>>>>%@", dict);
    [KK_FileModelEntity MKNetGET:@"/user/homepage" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            //            NSLog(@"好友功能>>>>>>>>用户主页  %@", responseObject);
            if (success) {
                success(responseObject);
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

//邀请好友
- (void)friendWithInvitation:(NSString *)userId success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSString *search = userId;
    
    if (!search) {
        search = @"";
    }
    NSDictionary *dict = @{@"access_token":SN_USER.access_token, @"invite_user_id":search};
    //    NSLog(@"dict>>>>%@", dict);
    [KK_FileModelEntity MKNetPOST:@"/friend/invite" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            //            NSLog(@"好友功能>>>>>>>>邀请好友  %@", responseObject);
            if (success) {
                success(responseObject);
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

//好友邀请信息列表
- (void)friendGetInvitationSuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSDictionary *dict = @{@"access_token":SN_USER.access_token};
    
    //    NSLog(@"dict>>>>%@", dict);
    [KK_FileModelEntity MKNetGET:@"/friend/invites" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            //            NSLog(@"好友功能>>>>>>>>好友邀请信息列表  %@", responseObject);
            NSArray *array = responseObject[@"data"];
            if (success) {
                success(array);
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

// 同意
- (void)friendPassInvitation:(NSString *)userId Success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSString *search = userId;
    
    if (!search) {
        search = @"";
    }
    NSDictionary *dict = @{@"access_token":SN_USER.access_token, @"invite_id":search};
    //    NSLog(@"dict>>>>%@", dict);
    [KK_FileModelEntity MKNetPOST:@"/friend/pass" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            //            NSLog(@"好友功能>>>>>>>>同意邀请好友  %@", responseObject);
            if (success) {
                success(responseObject);
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

// 拒绝
- (void)friendRejectInvitation:(NSString *)userId Success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSString *search = userId;
    
    if (!search) {
        search = @"";
    }
    NSDictionary *dict = @{@"access_token":SN_USER.access_token, @"invite_id":search};
    //    NSLog(@"dict>>>>%@", dict);
    [KK_FileModelEntity MKNetPOST:@"/friend/reject" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            //            NSLog(@"好友功能>>>>>>>>拒绝邀请好友  %@", responseObject);
            if (success) {
                success(responseObject);
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

// 删除好友请求
- (void)friendDeleteInvitation:(NSString *)userId Success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSString *search = userId;
    
    if (!search) {
        search = @"";
    }
    NSDictionary *dict = @{@"access_token":SN_USER.access_token, @"invite_id":search};
    //    NSLog(@"dict>>>>%@", dict);
    [KK_FileModelEntity MKNetPOST:@"/friend/unshow-invite" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            //            NSLog(@"好友功能>>>>>>>>删除邀请好友  %@", responseObject);
            if (success) {
                success(responseObject);
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

// 好友列表
- (void)friendGetListSuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSDictionary *dict = @{@"access_token":SN_USER.access_token};
    
    //    NSLog(@"dict>>>>%@", dict);
    [KK_FileModelEntity MKNetGET:@"/friend/list" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            //            NSLog(@"好友功能>>>>>>>> 我的好友列表  %@", responseObject);
            NSArray *array = responseObject[@"data"];
            if (success) {
                success(array);
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

// 备注好友
- (void)friendRemarkFriend:(NSString *)userId Remark:(NSString *)string Success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSString *remark = @"";
    
    if (string.length > 0) {
        remark = string;
    }
    NSDictionary *dict = @{@"access_token":SN_USER.access_token, @"friend_user_id":userId, @"remark":remark};
    [KK_FileModelEntity MKNetPOST:@"/friend/remark" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            //          NSLog(@"好友功能>>>>>>>>备注好友成功  %@", responseObject);
            if (success) {
                success(responseObject);
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

// 删除好友
- (void)friendDeleteFriend:(NSString *)userId Success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSString *search = userId;
    
    if (!search) {
        search = @"";
    }
    NSDictionary *dict = @{@"access_token":SN_USER.access_token, @"friend_user_id":search};
    //    NSLog(@"dict>>>>%@", dict);
    [KK_FileModelEntity MKNetPOST:@"/friend/delete" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            //            NSLog(@"好友功能>>>>>>>>删除好友  %@", responseObject);
            if (success) {
                success(responseObject);
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

//获取未读消息数量
- (void)friendSystemNoReadSuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSDictionary *dict = @{@"access_token":SN_USER.access_token};
    
    //    NSLog(@"dict>>>>%@", dict);
    [KK_FileModelEntity MKNetPOST:@"/notice/unread-count" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            //            NSLog(@"好友功能>>>>>>>>获取未读消息数量  %@", responseObject);
            NSDictionary *dic = responseObject[@"data"];
            NSInteger unread_count = [dic[@"unread_count"]integerValue];
            if (unread_count == 0) {
                SN_PublicClass.isFriendNewMessage = NO;
            } else {
                SN_PublicClass.isFriendNewMessage = YES;
            }
            if (success) {
                success(dic);
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

//消息全部标记为已读
- (void)friendSystemAllReadSuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSDictionary *dict = @{@"access_token":SN_USER.access_token};
    
    //    NSLog(@"dict>>>>%@", dict);
    [KK_FileModelEntity MKNetPOST:@"/notice/read-all" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            //            NSLog(@"好友功能>>>>>>>>全部已读  %@", responseObject);
            if (success) {
                success(responseObject);
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

// 用户消息列表/页码
- (void)friendGetSystemWithPage:(NSInteger)page Success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSDictionary *dict = @{@"access_token":SN_USER.access_token, @"page":StrByInt(page)};
    
    //    NSLog(@"dict>>>>%@", dict);
    [KK_FileModelEntity MKNetGET:@"/notice/list" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            //            NSLog(@"好友功能>>>>>>>> 用户消息列表  %@", responseObject);
            NSDictionary *dic = responseObject[@"data"];
            if (success) {
                success(dic);
            }
            if (page == 1) {
                //看完一页就发全部已读
                [self friendSystemAllReadSuccess:^(id object) {
                } fail:^(id object) {
                }];
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

//*************************好友健康*************************
- (void)friendClickWithType:(NSInteger)type userid:(NSString *)userid Success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSDictionary *dict = @{@"access_token":SN_USER.access_token, @"thumb_user_id":userid, @"type":StrByInt(type)};
    
    //    NSLog(@"dict>>>>%@", dict);
    [KK_FileModelEntity MKNetPOST:@"/friend/thumb" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            //            NSLog(@"好友功能>>>>>>>>点赞/鼓励  %@", responseObject);
            if (success) {
                success(responseObject);
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

//*************************用户信息*************************
- (void)friendUploadDataSuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    [SportModel getMaxDayStep];
    [SportModel getmaxContinueDays];
    [SportModel getMaxWeekStep];
    [SportModel getMaxMonthStep];
    
    NSMutableDictionary *userDic1 = [NSMutableDictionary dictionary];
    [userDic1 setObject:StrByInt(SN_USER.max_step) forKey:@"value"];
    [userDic1 setObject:SN_USER.max_step_date forKey:@"date"];
    
    NSMutableDictionary *userDic2 = [NSMutableDictionary dictionary];
    [userDic2 setObject:StrByInt(SN_USER.max_reach_times) forKey:@"value"];
    NSString *finish_days = [NSString stringWithFormat:@"%@-%@", [SN_USER.max_reach_start substringFromIndex:5], [SN_USER.max_reach_end substringFromIndex:5]];
    if (SN_USER.max_reach_times == 0) {
        finish_days = @"";
    }
    
    if (SN_USER.max_reach_times == 1) {
        finish_days = [SN_USER.max_reach_start substringFromIndex:5];
    }
    [userDic2 setObject:finish_days forKey:@"date"];
    
    NSMutableDictionary *userDic3 = [NSMutableDictionary dictionary];
    [userDic3 setObject:StrByInt(SN_USER.max_week_step) forKey:@"value"];
    [userDic3 setObject:[NSString stringWithFormat:@"%@-%@", [SN_USER.max_week_start substringFromIndex:5], [SN_USER.max_week_end substringFromIndex:5]] forKey:@"date"];
    
    NSMutableDictionary *userDic4 = [NSMutableDictionary dictionary];
    [userDic4 setObject:StrByInt(SN_USER.max_month_step) forKey:@"value"];
    [userDic4 setObject:[NSString stringWithFormat:@"%@", SN_USER.max_month] forKey:@"date"];
    
    NSArray *sportDataArray = [SportModel get30daysData:-29];
    NSArray *sleepDataArray = [SleepModel get30daysData:-29];
    NSArray *heartDataArray = [HeartModel get30daysData:-1];
    NSArray *OXDataArray    = [OxModel get30daysData:-1];
    NSArray *bpDataArray    = [BpModel get30daysData:-1];
    
    SportModel *model = SN_PublicClass.todaySport;
    //    NSArray    *sportDataArray = [SportModel get30daysData:-29];
    
    NSMutableArray *sportArray = [NSMutableArray array];
    for (SportModel *model in sportDataArray) {
        NSMutableDictionary *dic1 = [NSMutableDictionary dictionary];
        [dic1 setObject:StrByInt(model.step) forKey:@"steps"];
        [dic1 setObject:StrByInt(model.calory) forKey:@"calors"];
        [dic1 setObject:StrByInt(model.distance) forKey:@"distances"];
        [dic1 setObject:StrByInt(model.stepTarget) forKey:@"steptarget"];
        [dic1 setObject:StrByInt(model.stepDuration) forKey:@"durations"];
        [dic1 setObject:model.dateString forKey:@"datestring"];
        [sportArray addObject:dic1];
    }
    
    //    NSArray        *sleepDataArray = [SleepModel get30daysData:-29];
    NSMutableArray *sleepArray = [NSMutableArray array];
    for (SleepModel *model in sleepDataArray) {
        NSMutableDictionary *dic1 = [NSMutableDictionary dictionary];
        [dic1 setObject:StrByInt(model.deeps) forKey:@"deeps"];
        [dic1 setObject:StrByInt(model.lights) forKey:@"lights"];
        [dic1 setObject:StrByInt(model.sobers) forKey:@"sobers"];
        [dic1 setObject:model.dateString forKey:@"datestring"];
        [sleepArray addObject:dic1];
    }
    
    //    NSArray        *heartDataArray = [HeartModel get30daysData];
    NSMutableArray *heartArray = [NSMutableArray array];
    for (HeartModel *model in heartDataArray) {
        NSMutableDictionary *dic1          = [NSMutableDictionary dictionary];
        NSMutableArray      *allModelArray = [NSMutableArray array];
        for (int i = 0; i < model.heartAllValueArray.count; i++) {
            NSMutableDictionary *dicV = [NSMutableDictionary dictionary];
            [dicV setObject:[model.heartAllValueArray objectAtIndex:i] forKey:@"value"];
            [dicV setObject:[model.heartAllTimeArray objectAtIndex:i] forKey:@"time"];
            [allModelArray addObject:dicV];
        }
        
        [dic1 setObject:allModelArray forKey:@"heartdatas"];
        [dic1 setObject:StrByInt(model.heartMax) forKey:@"heartMax"];
        [dic1 setObject:StrByInt(model.heartMin) forKey:@"heartMIn"];
        [dic1 setObject:StrByInt(model.heartAve) forKey:@"heartAve"];
        [dic1 setObject:model.dateString forKey:@"datestring"];
        [heartArray addObject:dic1];
    }
    
    //    NSArray        *OXDataArray = [OxModel get30daysData];
    NSMutableArray *oxArray = [NSMutableArray array];
    for (OxModel *model in OXDataArray) {
        NSMutableDictionary *dic1 = [NSMutableDictionary dictionary];
        [dic1 setObject:StrByInt(model.oxAve) forKey:@"oxAve"];
        [dic1 setObject:StrByInt(model.oxMax) forKey:@"oxMax"];
        [dic1 setObject:StrByInt(model.oxMin) forKey:@"oxMin"];
        [dic1 setObject:model.dateString forKey:@"datestring"];
        
        NSMutableArray *allModelArray = [NSMutableArray array];
        for (int i = 0; i < model.oxsuArrayAuto.count; i++) {
            NSMutableDictionary *dicV      = [NSMutableDictionary dictionary];
            oxSubModel          *oxSuModel = [model.oxsuArrayAuto objectAtIndex:i];
            [dicV setObject:StrByInt(oxSuModel.oxValue) forKey:@"value"];
            NSArray *timeA = [oxSuModel.updateTime componentsSeparatedByString:@" "];
            [dicV setObject:[timeA lastObject] forKey:@"time"];
            [allModelArray addObject:dicV];
        }
        [dic1 setObject:allModelArray forKey:@"oxdatas"];
        [oxArray addObject:dic1];
    }
    
    //    NSArray        *bpDataArray = [BpModel get30daysData];
    NSMutableArray *bpArray = [NSMutableArray array];
    for (BpModel *model in bpDataArray) {
        NSMutableDictionary *dic1 = [NSMutableDictionary dictionary];
        [dic1 setObject:StrByInt(model.SBPAve) forKey:@"SBPave"];
        [dic1 setObject:StrByInt(model.DBPAve) forKey:@"DBPave"];
        [dic1 setObject:model.dateString forKey:@"datestring"];
        
        NSMutableArray *allModelArray = [NSMutableArray array];
        for (int i = 0; i < model.bpSuArray.count; i++) {
            NSMutableDictionary *dicV      = [NSMutableDictionary dictionary];
            bpSubModel          *bpSuModel = [model.bpSuArray objectAtIndex:i];
            [dicV setObject:StrByInt(bpSuModel.SBPValue) forKey:@"SBPValue"];
            [dicV setObject:StrByInt(bpSuModel.DBPValue) forKey:@"DBPValue"];
            NSArray *timeA = [bpSuModel.updateTime componentsSeparatedByString:@" "];
            [dicV setObject:[timeA lastObject] forKey:@"time"];
            [allModelArray addObject:dicV];
        }
        [dic1 setObject:allModelArray forKey:@"bpdatas"];
        [bpArray addObject:dic1];
    }
    
    SleepModel *sleepModel = SN_PublicClass.todaySleep;
    HeartModel *heartModel = SN_PublicClass.todayHeart;
    OxModel    *oxModel    = SN_PublicClass.todayOx;
    BpModel    *bpModel    = SN_PublicClass.todayBp;
    
    NSDictionary *dict = @{@"access_token":SN_USER.access_token, @"today_date":model.dateString, @"today_step":StrByInt(model.step), @"today_distance":StrByInt(model.distance), @"today_calory":StrByInt(model.calory), @"today_duration":StrByInt(model.stepDuration), @"max_step":[userDic1 YYJSONString], @"finish_days":[userDic2 YYJSONString], @"max_week":[userDic3 YYJSONString], @"max_month":[userDic4 YYJSONString], @"sport_history":[sportArray YYJSONString], @"sleep_history":[sleepArray YYJSONString], @"heart_history":[heartArray YYJSONString], @"ox_history":[oxArray YYJSONString], @"bp_history":[bpArray YYJSONString], @"today_deeps":StrByInt(sleepModel.deeps), @"today_lights":StrByInt(sleepModel.lights), @"today_wakes":StrByInt(sleepModel.sobers), @"today_avg":StrByInt(heartModel.heartAve), @"today_highest":StrByInt(heartModel.heartMax), @"today_lowest":StrByInt(heartModel.heartMin), @"today_ox_max":StrByInt(oxModel.oxMax), @"today_ox_min":StrByInt(oxModel.oxMin), @"today_ox_avg":StrByInt(oxModel.oxAve), @"today_dbp_avg":StrByInt(bpModel.DBPAve), @"today_sbp_avg":StrByInt(bpModel.SBPAve), @"today_sleeps":StrByInt(sleepModel.durations)};
    
    //    NSLog(@"dict>>>>>%@",dict);
    [KK_FileModelEntity MKNetPOST:@"/user/sync" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            NSLog(@"好友功能>>>>>>>>上传用户的统计数据 %@", responseObject);
            if (success) {
                success(responseObject);
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

- (void)friendGetDataWithUserid:(NSString *)userid Success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSString *search = userid;
    if (!search) {
        search = @"";
    }
    NSDictionary *dict = @{@"access_token":SN_USER.access_token, @"user_id":search};
    [KK_FileModelEntity MKNetGET:@"/user/stat" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            NSLog(@"好友功能>>>>>>>>获取用户的统计数据 %@", responseObject);
            if (success) {
                success(responseObject);
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

//*************************健康食谱*************************
// 匹配食物
- (void)FoodSearchWithFoodName:(NSString *)foodName Success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail
{
    NSString *search = foodName;
    if (!search) {
        search = @"";
    }
    NSDictionary *dict = @{@"access_token":SN_USER.access_token, @"key":search};
    NSLog(@"dic>>>>>%@",dict);
    [KK_FileModelEntity MKNetGET:@"/meal/match-food" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            NSLog(@"健康食谱 匹配食材成功 %@", responseObject);
            NSArray *foodArray = responseObject[@"data"];
            if (success) {
                success(foodArray);
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

// 新增用餐
- (void)FoodAddWithFoodModel:(FoodEatModel *)model Success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail
{
    NSDictionary *dict  = @{@"access_token":SN_USER.access_token,@"date": model.date,@"calory":[NSString stringWithFormat:@"%.1f",model.caloryTotal],@"foods":[SN_FoodClass.foodListArray YYJSONString]};
    
    NSLog(@"新增的用餐为>>>>>>%@",dict);
    [KK_FileModelEntity MKNetPOST:@"/meal/add" params:dict success:^(id responseObject) {
        HIDDENMBProgressHUD
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            if (success) {
                success(nil);
            }
        }
        else
        {
            
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

// 编辑用餐
- (void)FoodEditWithFoodModel:(FoodEatModel *)model Success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail
{
    NSInteger mealId = model.userId;
     NSDictionary *dict  = @{@"access_token":SN_USER.access_token,@"id": StrByInt(mealId),@"calory":[NSString stringWithFormat:@"%.1f",model.caloryTotal],@"foods":[SN_FoodClass.foodListArray YYJSONString],};
    NSLog(@"编辑的用餐为>>>>>>%@",dict);
    [KK_FileModelEntity MKNetPOST:@"/meal/update" params:dict success:^(id responseObject) {
        HIDDENMBProgressHUD
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            if (success) {
                success(nil);
            }
        }
        else
        {
            
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

// 删除用餐
- (void)FoodDeleteWithFoodModel:(FoodEatModel *)model Success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail
{
    NSInteger deleteId = model.userId;
    NSString *idString = StrByInt(deleteId);
    NSDictionary *dict  = @{@"access_token":SN_USER.access_token,@"id":idString};
    NSLog(@"删除的用餐为>>>>>>%@",dict);
    [KK_FileModelEntity MKNetPOST:@"/meal/remove" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            if (success) {
                success(nil);
            }
            HIDDENMBProgressHUD
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

// 获取当日食谱
- (void)foodListSearchWithDate:(NSString *)dateString Success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail
{
    NSString *search = dateString;
    if (!search) {
        search = @"";
    }
    NSDictionary *dict = @{@"access_token":SN_USER.access_token, @"date":search};
    NSLog(@"dict>>>>%@",dict);
    
    [KK_FileModelEntity MKNetGET:@"/meal/daily-list" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            NSLog(@"健康食谱 获取今日的用餐记录 %@", responseObject);
            if (success) {
                success(responseObject);
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

// 开始日期-
- (void)foodListSearchWithStateDate:(NSString *)startDateString Success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail
{
    NSString *begin_date = startDateString;
    NSString *end_date = [[NSDate date]dateToDayString];
    
    if (!begin_date) {
        begin_date = end_date;
    }
    
    NSDictionary *dict = @{@"access_token":SN_USER.access_token, @"begin_date":begin_date,@"end_date":end_date};
    [KK_FileModelEntity MKNetGET:@"/meal/history-list" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            NSLog(@"健康食谱  获取食谱列表 %@", responseObject);
            NSArray *array = responseObject[@"data"];
            if (array.count > 0) {
                for (NSDictionary *dic in array) {
                    NSString *dateString = dic[@"date"];
                    [FoodModel updateModelWithDic:dic withDateString:dateString];
                }
            }
            if (success) {
                success(responseObject);
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

// 步数分布统计
- (void)sortGetStepWithSuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail
{
    NSDictionary *dict = @{@"access_token":SN_USER.access_token};
    [KK_FileModelEntity MKNetGET:@"/sport/distribution" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            NSLog(@"好友排名  步数分布 %@", responseObject);
            NSArray *array = responseObject[@"data"];
            if (array.count > 0) {
                if (success) {
                    success(array);
                }
                [SortModel updateModelWithDic:array withDateString:[[NSDate date]dateToDayString]];
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

// 睡眠时长
- (void)sortGetSleepTimeWithSuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail
{
    NSDictionary *dict = @{@"access_token":SN_USER.access_token};
    [KK_FileModelEntity MKNetGET:@"/sleep/duration-distribution" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            NSLog(@"好友排名  睡眠时长 %@", responseObject);
            NSArray *array = responseObject[@"data"];
            if (array.count > 0) {
                if (success) {
                    success(array);
                }
                [SortModel updateModelWithSleepDurationDic:array withDateString:[[NSDate date]dateToDayString]];
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

- (void)getCodeWithSuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSDictionary *dict = @{@"access_token":SN_USER.access_token};
    [KK_FileModelEntity MKGET:@"/user/auth-code" params:dict success:^(id object) {
        NSDictionary *result = [self dictionaryWithJsonString:object];
        if (result[@"ret"] && [result[@"ret"] intValue] == 0) {
            NSString *auth_code = [result[@"data"] objectForKey:@"auth_code"];
            if (success) {
                success(auth_code);
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}

// 入睡时间
- (void)sortGetSleepStartTimeWithSuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail
{
    NSDictionary *dict = @{@"access_token":SN_USER.access_token};
    [KK_FileModelEntity MKNetGET:@"/sleep/fall-distribution" params:dict success:^(id responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            NSLog(@"好友排名  入睡时间 %@", responseObject);
            NSArray *array = responseObject[@"data"];
            if (array.count > 0) {
                if (success) {
                    success(array);
                }
                [SortModel updateModelWithSleepStartDic:array withDateString:[[NSDate date]dateToDayString]];
            }
        }
    } fail:^(id object) {
        if (fail) {
            fail(nil);
        }
    }];
}


- (void)showHUD:(NSString *)info withTime:(CGFloat)time
{
    HIDDENMBProgressHUD
    SHOWMBProgressHUDIndeterminate(info, nil, nil);
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(stopHIDDENMBProgressHUD) object:nil];
    [self performSelector:@selector(stopHIDDENMBProgressHUD) withObject:nil afterDelay:time];
}

- (void)stopHIDDENMBProgressHUD
{
    HIDDENMBProgressHUD
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData       *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dic      = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    return dic;
}

- (id)arrayWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData       *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:nil];
    return jsonObject;
}


@end

